<?php
/**
 * User：liujun
 * Date：2022/3/4
 * Time：10:24 PM
 */

namespace Encore\Admin\Controllers;

use Encore\Admin\Layout\Content;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class ErrorLogController extends AdminController
{
    /**
     * 异常日志
     * @param Content $content
     * @param $file
     * @return Content
     * @throws \Exception
     */
    public function logs(Content $content, $file = null): Content
    {
        if ($file === null) {
            $file = (new LogViewer())->getLastModifiedLog();
        }
        $offset = request('offset');
        $viewer = new LogViewer($file);
        return $content
            ->title(Str::of($viewer->getFilePath())->afterLast('/')->upper())
            ->body(view('admin::errorLog',[
                'logs'      => $viewer->fetch($offset),
                'logFiles'  => $viewer->getLogFiles(),
                'fileName'  => $viewer->file,
                'end'       => $viewer->getFilesize(),
                'tailPath'  => route('log-viewer-tail', ['file' => $viewer->file]),
                'prevUrl'   => $viewer->getPrevPageUrl(),
                'nextUrl'   => $viewer->getNextPageUrl(),
                'filePath'  => $viewer->getFilePath(),
                'size'      => static::bytesToHuman($viewer->getFilesize()),
            ]));

    }

    public function tail(Request $request, $file)
    {
        $offset = $request->get('offset');

        $viewer = new LogViewer($file);

        list($pos, $logs) = $viewer->tail($offset);

        return compact('pos', 'logs');
    }

    protected static function bytesToHuman($bytes): string
    {
        $units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];

        for ($i = 0; $bytes > 1024; $i++) {
            $bytes /= 1024;
        }

        return round($bytes, 2).' '.$units[$i];
    }
}